package com.mapfinal.mapcache;

import java.awt.image.BufferedImage;
import java.util.Map;

import com.google.common.collect.Maps;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.mapfinal.mapcache.cache.MapFileCachePersistence;
import com.mapfinal.mapcache.cache.MapSqliteCachePersistence;
import com.mapfinal.server.MapfinalServerConfig;
import com.mapfinal.server.MapfinalServerConsts;
import com.mapfinal.server.service.tile.TileParam;

public class MapServerManager {

	private static MapServerManager manage = null;
	
	public static MapServerManager me() {
		if(manage==null) {
			manage = new MapServerManager();
		}
		return manage;
	}
	
	private MapCachePersistence mapCache;
	private Map<String, MapServer> mapServers;
	
	public MapServerManager() {
		// TODO Auto-generated constructor stub
		mapServers = Maps.newHashMap();
	}
	
	public void registerServer(String name, MapServer mapServer) {
		mapServers.put(name, mapServer);	
	}
	
	
	public BufferedImage getEmptyImage() {
		BufferedImage image = Lambkit.getCache().get("MAP_CACHE_TILE", "EMPTY_IMAGE");
		if(image==null) {
			image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);
			Lambkit.getCache().put("MAP_CACHE_TILE", "EMPTY_IMAGE", image);
		}
		return image;
	}


	public MapServer getMapSever(String serverType) {
		// TODO Auto-generated method stub
		return mapServers.get(serverType);
	}
	
	public MapCachePersistence getMapCache() {
		// TODO Auto-generated method stub
		if(mapCache==null) {
			MapfinalServerConfig config = Lambkit.config(MapfinalServerConfig.class);
			switch (config.getMapCacheType()) {
			case MapfinalServerConsts.SQLITE:
				mapCache = new MapSqliteCachePersistence();
				break;
			default:
				mapCache = new MapFileCachePersistence();
				break;
			}
		}
		return mapCache;
	}
	
	public TileParam getTile(Controller controller) {
		// TODO Auto-generated method stub
		String serverType = controller.get("type");
		String server = controller.getPara("server");
		String layer = controller.getPara("layer");
		
		String crs = controller.getPara("crs", "EPSG:3857");
		Integer zoom = controller.getParaToInt("z");
		Integer x = controller.getParaToInt("x");
		Integer y = controller.getParaToInt("y");
		String time = controller.getPara("time");
		String styles = controller.getPara("styles", "");
		String pathName = controller.getPara("pn");
		TileParam tile = new TileParam(x, y, zoom, crs);
		if (StrKit.isBlank(pathName) && StrKit.notBlank(time)) {
			pathName = time;
		}
		if(StrKit.notBlank(serverType)) {
			tile.setServerType(serverType);
		}
		tile.setServer(server);
		tile.setLayer(layer);
		tile.setStyles(styles);
		tile.setPathName(pathName);
		return tile;
	}
}
